import axios from 'axios'

const dic = {
  api: 'buyer/off-product',
  picture: 'buyer/picture',
  topic: 'buyer/topic',
  user: 'buyer/user',
  buyer: 'buyer/buyer-product',
  demand: 'buyer/demand',
  platform: 'buyer/platform'
}

axios.interceptors.request.use(request => {
  const token = sessionStorage.getItem('token') || window.token

  if (!token && request.url !== '/user/v1/login') {
    axios.handlers.unauthenticated()
  }

  let urlArr = request.url.split('/')

  let firstUrl = urlArr[1]
  console.log(dic[firstUrl])
  if (firstUrl) {
    urlArr[1] = dic[firstUrl]
  }
  let url = urlArr.join('/')

  console.log(url)
  request.url = url

  request.headers.accessToken = token
  return request
})

axios.interceptors.response.use(
  response => {
    if (response.config.url !== '/api/login' &&
      (response.data.status === -3)) {
      axios.handlers.unauthenticated()
      return Promise.reject('Login invalid.')
    }

    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

axios.install = (Vue, handlers) => {
  Vue.prototype.$axios = axios
  axios.handlers = {}
  axios.handlers.unauthenticated = handlers.unauthenticated
}

axios.postForm = (url, data) => {
  const form = Reflect.ownKeys(data || {}).reduce((formData, key) => {
    formData.append(key, data[key])
    return formData
  }, new FormData())
  const options = {
    url: url,
    method: 'post',
    data: form,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
  return axios(options)
}

export default axios
